import { RouteRecordRaw } from "vue-router";
import { useMenuStore } from "@/store/modules/menu";
import { useUserStore } from "@/store/modules/user";
import router from "./index";
import { whiteList } from "@/config";

router.beforeEach(async (to, from, next) => {
  const menuStore = useMenuStore();
  const { token } = useUserStore();
  if (token) {
    // 如果没有菜单列表，就重新请求菜单列表并添加动态路由
    if (!menuStore.menusList.length) {
      await menuStore.getMenus();
      menuStore.menusList.forEach(item => {
        if (item.meta.isFull) {
          router.addRoute(item as unknown as RouteRecordRaw);
        } else {
          router.addRoute("layout", item as unknown as RouteRecordRaw);
        }
      });
      return next({ ...to, replace: true });
    } else {
      next();
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next("/login");
    }
  }
});

/**
 * @description 路由跳转错误
 * */
router.onError(error => {
  console.warn("路由错误", error.message);
});
